import { Connection, createConnection, EntityManager, Transaction, TransactionManager } from 'typeorm';
import { LoggerUtility } from '../logger/logger.utility';

export class MySQLUtils {
    public static getConnection() {
        if (!MySQLUtils.connection) {
            MySQLUtils.connection = createConnection();
        }
        return MySQLUtils.connection;
    }

    public static Save(connection: Connection, savedEntity): Promise<{ flag: boolean, newEntity: any }> {
        return connection.manager.save(savedEntity).then((newEntity) => {
            return { flag: true, newEntity };
        }).catch((error) => {
            LoggerUtility.error('MySQL Save error:', error);
            return { flag: false, newEntity: error };
        });
    }

    // @Transaction()
    public static SaveTransaction(connection: Connection, paras: any): Promise<{ flag: boolean, output: any }> {
        return connection.manager.transaction(async (transactionalEntityManager) => {
            paras.forEach(async (item) => {
                await transactionalEntityManager.save(item);
            });
            return { flag: true, output: 'save transation successed' };
        }).catch((error) => {
            LoggerUtility.error('MySQL SaveTransaction error:', error);
            return { flag: false, output: error };
        });
    }

    public static Delete(connection: Connection, contract: any, idOrObj: any): Promise<{ flag: boolean, output: any }> {
        return connection.manager.delete(contract, idOrObj).then(() => {
            return { flag: true, output: undefined };
        }).catch((error) => {
            LoggerUtility.error('MySQL Delete error:', error);
            return { flag: false, output: error };
        });
    }

    public static DeleteTransaction(connection: Connection, contract: any, idOrObjs: any[])
        : Promise<{ flag: boolean, output: any }> {
        return connection.manager.transaction(async (transactionalEntityManager) => {
            idOrObjs.forEach(async (idOrObj) => {
                await transactionalEntityManager.delete(contract, idOrObj);
            });
            return { flag: true, output: 'delete transation successed' };
        }).catch((error) => {
            LoggerUtility.error('MySQL DeleteTransaction error:', error);
            return { flag: false, output: error };
        });
    }

    private static connection: Promise<Connection>;
}
